import csv
import os
from datetime import datetime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
import django
django.setup()
from web.models import Category,Topic

def add():
    c = Category()
    c.name = "测试栏目"
    c.type = 0
    c.create_date = datetime.now()
    c.save()

def load():
    c = Category.objects.get(pk=1)
    print(f'{c.name}\t{c.type}\t{c.create_date}')
def update():
    c = Category.objects.get(pk=1)
    c.type = 1
    c.save()
def find():
    cs = Category.objects.all()
    for c in cs:
        print(f'{c.name}\t{c.type}\t{c.create_date}')
def delete():
    c = Category.objects.get(pk=2)
    c.delete()

def batch_add():
    with open("./res/category.csv", "r", encoding="utf-8") as f:
        fc = csv.reader(f)
        for f in fc:
            c = Category()
            c.name = f[0]
            c.type = f[1]
            c.href = f[2]
            c.is_nav = f[3]
            c.is_index = f[4]
            c.create_date = datetime.now()
            if f[5] != 0:
                pc = Category()
                pc.id = f[5]
                c.parent = pc
            else:
                c.parent = None
            c.save()
def relation_query():
    #可以直接查询出父类
    c = Category.objects.get(id=28)
    print(c)

def relation_query2():
    c = Category.objects.get(id=27)
    #对象的xx_set可以获取它的子关联
    childs = c.category_set.all() #可以获取所有的子类
    for child in childs:
        print(child)
if __name__ == '__main__':
    relation_query2()
